#include "tile_table_delegate.h"

#include <QDebug>
#include <QPainter>

#include "qvariant_utils.h"
#include "tile_sheet.h"
#include "tile_table_model.h"

TileTableDelegate::TileTableDelegate(QObject* parent)
    : QStyledItemDelegate(parent),
      scale_factor_(2.0) {}

void TileTableDelegate::paint(QPainter* painter,
                              const QStyleOptionViewItem& option,
                              const QModelIndex& index) const {
  if (option.state & QStyle::State_Selected) {
    painter->save();
    painter->setOpacity(0.5);
    painter->fillRect(option.rect, option.palette.highlight());
    painter->restore();
  }
  QPixmap tile_pixmap = index.model()->data(index, Qt::DisplayRole).value<QPixmap>();
  painter->drawPixmap(option.rect, tile_pixmap);
  if (option.state & QStyle::State_Selected) {
    QPen outline_pen;
    outline_pen.setBrush(option.palette.highlight());
    outline_pen.setWidth(2);
    outline_pen.setJoinStyle(Qt::MiterJoin);
    painter->setPen(outline_pen);
    painter->drawRect(option.rect.adjusted(1, 1, -1, -1));
  }
}

QSize TileTableDelegate::sizeHint(const QStyleOptionViewItem& option,
                                  const QModelIndex& index) const {
  Q_UNUSED(option);
  if (!index.model()) {
    return QSize();
  }
  TileSheet* sheet = QVariantPtr<TileSheet>::asPointer(
      index.model()->data(index, TileTableModel::kTileSheetRole));
  return sheet->tileSize() * scale_factor_;
}

void TileTableDelegate::setScaleFactor(qreal factor) {
  scale_factor_ = factor;
  emit sizeHintChanged(QModelIndex());
}
